package com.me.singleton;

/**
 * @author inttom
 * @date 2022/2/13
 *
 * 连线程安全都解决不了
 * 结论: 在实际开发中,**不能用这种方式**
 */
public class SingletonTest05 {
    public static void main(String[] args) {
        new Thread(new MyThread3()).start();
        new Thread(new MyThread3()).start();
    }
}

class MyThread3 implements Runnable {

    @Override
    public void run() {
        Singleton5 instance = Singleton5.getInstance();
        System.out.println(Thread.currentThread().getName() + ": " + instance.hashCode());
    }
}

/**
 * 懒汉式(线程安全,同步代码块)
 */
class Singleton5 {
    private static Singleton5 instance;
    private Singleton5() {
    }

    /**
     * 提供一个静态的公有方法,当使用到该方法的时候,才会去创建 instance
     * 懒汉式
     */
    public static Singleton5 getInstance() {
        if (instance == null) {
            synchronized (Singleton5.class) {
                instance = new Singleton5();
            }
        }
        return instance;
    }
}


